package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.ResponseObject.ColorResponse;
import com.ugoodtech.mdcc.client.controller.ResponseObject.CustomerResponse;
import com.ugoodtech.mdcc.client.controller.ResponseObject.PaintResponse;
import com.ugoodtech.mdcc.client.controller.ResponseObject.ServiceResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.helper.SearchVoId;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.CustomerService;
import com.ugoodtech.mdcc.core.service.SearchPermissionsService;
import io.swagger.annotations.*;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.*;

@Api(description = "报告一览接口")
@RestController
@RequestMapping("/report")
public class GetAllReport {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private SearchPermissionsService searchPermissionsService;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @ApiOperation("查询通过审核的基础报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "color", method = RequestMethod.GET)
    public JsonResponse color(Principal principal,
                              Pageable pageable,
                              @ApiParam("省") @RequestParam(value = "province", required = false) String province,
                              @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                              @ApiParam("类型") @RequestParam(value = "category", required = false) String category,
                              @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
                              @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName,
                              @ApiParam("创建人员姓名") @RequestParam(value = "userName", required = false) String userName,
                              @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) String customerStat,
                              @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) String customerType,
                              @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String paintBrand,
                              @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
                              @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                              @ApiParam("起始时间") @RequestParam(value = "startTime", required = false) Long startTime,
                              @ApiParam("结束时间") @RequestParam(value = "endTime", required = false) Long endTime,
                              @ApiParam("是否填写满意度：true:填写，false:未填写") @RequestParam(value = "type", required = false) Boolean type,
                              @ApiParam("所属部门") @RequestParam(value = "department", required = false) String department,
                              @ApiParam("是否填写精益钣喷：true:填写，false:未填写") @RequestParam(value = "paintType", required = false) Boolean paintType,
                              @ApiParam("该维修站是否使用我司增值服务") @RequestParam(value = "payService", required = false) String payService,
                              @ApiParam("油漆配送时效") @RequestParam(value = "sentTime", required = false) String sentTime,
                              @ApiParam("经销商上门服务周期") @RequestParam(value = "serviceTime", required = false) String serviceTime
    ) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        SearchVoId searchVoId;
        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
        if (clientUser.getUserType().equals(UserType.dealers)) {
            searchVoId = searchPermissionsService.getDealersStationId(userProfile, province, brand);
        } else {
            searchVoId = searchPermissionsService.searchColorReportByProvinceBrand(userProfile, province, brand);
        }
        if (searchVoId.getResultStationReportId().isEmpty()) {
            Page<ColorResponse> page = new PageImpl(new ArrayList(), pageable, 0L);
            return JsonResponse.successResponseWithPageData(page);
        }
        String[] cities = null;
        String[] categories = null;
        Long[] customerStats = null;
        Long[] customerTypes = null;
        String[] paintBrands = null;
        String[] productPositions = null;
        String[] departments = null;

        if (!StringUtils.isEmpty(city)){
            cities = city.split(",");
        }
        if (!StringUtils.isEmpty(category)){
            categories = category.split(",");
        }
        if (!StringUtils.isEmpty(paintBrand)){
            paintBrands = paintBrand.split(",");
        }
        if (!StringUtils.isEmpty(productPosition)){
            productPositions = productPosition.split(",");
        }
        if (!StringUtils.isEmpty(customerStat)){
            customerStats = (Long[]) ConvertUtils.convert(customerStat.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(customerType)){
            customerTypes = (Long[]) ConvertUtils.convert(customerType.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(department)){
            departments = department.split(",");
        }
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
        builder.and(qStationReport.station.checkStation.eq(true));
        builder.and(qStationReport.station.enabled.eq(true));
        builder.and(qStationReport.id.in(searchVoId.getResultStationReportId()));
        if (customerStats != null) {
            builder.and(qStationReport.station.customerStat.in(customerStats));
        }
        if (customerTypes != null) {
            builder.and(qStationReport.station.customerType.in(customerTypes));
        }
        if (paintBrands!=null) {
            BooleanBuilder paintBrandBuilder = new BooleanBuilder();
            for (String pBrand:paintBrands){
                paintBrandBuilder.or(qStationReport.station.paintBrand.like("%" + pBrand + "%"));
            }
            builder.and(paintBrandBuilder);
        }
        if (productPositions!=null) {
            BooleanBuilder ppBuilder = new BooleanBuilder();
            for (String pp:productPositions){
                ppBuilder.or(qStationReport.station.productPosition.like("%" + pp + "%"));
            }
            builder.and(ppBuilder);
        }
        if (cities!=null) {
            builder.and(qStationReport.station.city.in(cities));
        }
        if (categories!=null) {
            builder.and(qStationReport.station.category.in(categories));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStationReport.station.name.like("%" + stationName + "%"));
        }
        if (startTime != null){
            builder.and(qStationReport.creationTime.goe(new Date(startTime)));
        }
        if (endTime != null){
            builder.and(qStationReport.creationTime.lt(new Date(endTime)));
        }
        if (paintType != null){
            builder.and(qStationReport.station.isPaint.eq(paintType?1:0));
        }
        if (StringUtils.isNotEmpty(userName) || departments != null) {
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
            boolean flag = false;
            if (StringUtils.isNotEmpty(userName)) {
                flag = true;
                booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            }
            if (departments != null){
                flag = true;
                booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
                booleanBuilder.and(qUserProfile.user.userType.in(UserType.admin,UserType.dealers,UserType.insiders));
                for (String str:departments){
                    booleanBuilder.or(qUserProfile.departmentList.any().name.eq(str));
                }
            }
            if (flag) {
                List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
                if (userProfileList == null || userProfileList.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> userIds = new ArrayList<>();
                for (UserProfile user : userProfileList) {
                    userIds.add(user.getUser().getId());
                }
                BooleanBuilder colorBuilder = new BooleanBuilder();
                colorBuilder.and(qStationColorReport.deleted.eq(false));
                colorBuilder.and(qStationColorReport.enabled.eq(true));
                colorBuilder.and(qStationColorReport.stationReport.station.report_finished.in(1, 2, 3));
                colorBuilder.and(qStationColorReport.stationReport.user.id.in(userIds));
                List<StationColorReport> list = (List<StationColorReport>) stationColorReportRepository.findAll(colorBuilder);
                if (list == null || list.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> ids = new ArrayList<>();
                for (StationColorReport report : list) {
                    if (report.getReportId() != null) {
                        ids.add(Long.parseLong(report.getReportId()));
                    }
                }
                builder.and(qStationReport.id.in(ids));
            }
        }
        if (StringUtils.isNotEmpty(stationNum)) {
            builder.and(qStationReport.station.stationNum.like("%" + stationNum + "%"));
        }

        if (payService != null || sentTime!=null || serviceTime!=null){
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            BooleanBuilder builderStationColor = new BooleanBuilder();
            builderStationColor.and(qStationColorReport.deleted.eq(false));
            builderStationColor.and(qStationColorReport.enabled.eq(true));
            boolean flag = false;
            if (payService!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+payService+"%"));
            }
            if (sentTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+sentTime+"%"));
            }
            if (serviceTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+serviceTime+"%"));
            }
            if (flag) {
                List<StationColorReport> stationColorReports = (List<StationColorReport>) stationColorReportRepository.findAll(builderStationColor);
                if (stationColorReports == null || stationColorReports.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> Ids = new ArrayList<>();
                for (StationColorReport report : stationColorReports) {
                    Ids.add(report.getStationReport().getStation().getId());
                }
                builder.and(qStationReport.station.id.in(Ids));
            }
        }
        if (type != null) {
            QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
            BooleanBuilder builderCustomer = new BooleanBuilder();
            builderCustomer.and(qCustomerRegularReport.deleted.eq(false));
            builderCustomer.and(qCustomerRegularReport.enabled.eq(true));
            builderCustomer.and(qCustomerRegularReport.type.eq(type));
            List<CustomerRegularReport> customerRegularReports = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builderCustomer);
            if (customerRegularReports == null || customerRegularReports.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            Long[] ids = new Long[customerRegularReports.size()];
            for (int i = 0; i < customerRegularReports.size(); i++) {
                ids[i] = customerRegularReports.get(i).getRegularReport().getId();
            }
            builder.and(qStationReport.id.in(ids));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<StationReport> stationReportPage = stationReportRepository.findAll(builder, pageable);
        if (stationReportPage == null){
            return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
        }
        List<ColorResponse> customerResponseList = new ArrayList<>();
        for (StationReport report : stationReportPage.getContent()) {
            userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            ColorResponse response = new ColorResponse(report, userProfile.getRealName());
            customerResponseList.add(response);
        }
        Page<ColorResponse> page = new PageImpl(customerResponseList, pageable, customerResponseList.size());
        return JsonResponse.successResponseWithPageData(page);
    }

    @ApiOperation("按条件查询通满意度报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "customer", method = RequestMethod.GET)
    public JsonResponse customer(Principal principal,
                                 Pageable pageable,
                                 @ApiParam("省") @RequestParam(value = "province", required = false) String province,
                                 @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                 @ApiParam("类型") @RequestParam(value = "category", required = false) String category,
                                 @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
                                 @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) String customerStat,
                                 @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) String customerType,
                                 @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String paintBrand,
                                 @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
                                 @ApiParam("服务项目") @RequestParam(value = "serviceType", required = false) String serviceType,
                                 @ApiParam("服务次数") @RequestParam(value = "serviceNum", required = false) Integer serviceNum,
                                 @ApiParam("常规服务报告状态") @RequestParam(value = "reportStatus", required = false) String reportStatus,
                                 @ApiParam("需跟进报告处理状态") @RequestParam(value = "serviceReportStatus", required = false) String serviceReportStatus,
                                 @ApiParam("所属部门") @RequestParam(value = "department", required = false) String department,
                                 @ApiParam("是否填写精益钣喷：true:填写，false:未填写") @RequestParam(value = "paintType", required = false) Boolean paintType,
                                 @ApiParam("该维修站是否使用我司增值服务") @RequestParam(value = "payService", required = false) String payService,
                                 @ApiParam("油漆配送时效") @RequestParam(value = "sentTime", required = false) String sentTime,
                                 @ApiParam("经销商上门服务周期") @RequestParam(value = "serviceTime", required = false) String serviceTime,
                                 @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName,
                                 @ApiParam("服务开始时间") @RequestParam(value = "serviceStartTime", required = false) Long serviceStartTime,
                                 @ApiParam("服务结束时间") @RequestParam(value = "serviceEndTime", required = false) Long serviceEndTime,
                                 @ApiParam("提交报告时间") @RequestParam(value = "startTime", required = false) Long startTime,
                                 @ApiParam("提交报告结束时间") @RequestParam(value = "endTime", required = false) Long endTime,
                                 @ApiParam("外勤人员关键字") @RequestParam(value = "userName", required = false) String userName,
                                 @ApiParam("满意度打分") @RequestParam(value = "score", required = false) String score,
                                 @ApiParam("是否进行满意度回访") @RequestParam(value = "isManaged", required = false) String isManaged,
                                 @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        Page<CustomerRegularReport> reportList = customerService.
                getCustomerReport(clientUser.getId(), pageable, province,city, category, brand,customerStat,customerType,paintBrand,
                        productPosition,serviceType,serviceNum,reportStatus,serviceReportStatus,department,paintType,payService,sentTime,serviceTime,
                        stationName, serviceStartTime,serviceEndTime, startTime, endTime, userName, score, isManaged, stationNum);
        if (reportList == null) {
            return JsonResponse.errorResponseWithError("抱歉", "查询失败");
        }
        List<CustomerResponse> responseList = new ArrayList<>();
        for (CustomerRegularReport customerRegularReport : reportList) {
            User user = customerRegularReport.getRegularReport().getUser();
            UserProfile userProfile1 = userProfileRepository.findByUserId(user.getId());
            CustomerResponse response = new CustomerResponse(customerRegularReport, userProfile1.getRealName());
            responseList.add(response);
        }
        Page<CustomerResponse> page = new PageImpl(responseList, pageable, reportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    @ApiOperation("查询常规服务报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "service", method = RequestMethod.GET)
    public JsonResponse service(Principal principal,
                                Pageable pageable,
                                @ApiParam("省") @RequestParam(value = "province", required = false) String province,
                                @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                @ApiParam("类型") @RequestParam(value = "category", required = false) String category,
                                @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
                                @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName,
                                @ApiParam("服务开始时间") @RequestParam(value = "serviceStartTime", required = false) Long serviceStartTime,
                                @ApiParam("服务结束时间") @RequestParam(value = "serviceEndTime", required = false) Long serviceEndTime,
                                @ApiParam("报告起始提交时间") @RequestParam(value = "startTime", required = false) Long startTime,
                                @ApiParam("报告结束提交时间") @RequestParam(value = "endTime", required = false) Long endTime,
                                @ApiParam("服务项目") @RequestParam(value = "serviceType", required = false) String serviceType,
                                @ApiParam("服务次数") @RequestParam(value = "serviceNum", required = false) Integer serviceNum,
                                @ApiParam("常规服务报告状态") @RequestParam(value = "reportStatus", required = false) String reportStatus,
                                @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                                @ApiParam("所属部门") @RequestParam(value = "department", required = false) String department,
                                @ApiParam("是否填写精益钣喷：true:填写，false:未填写") @RequestParam(value = "paintType", required = false) Boolean paintType,
                                @ApiParam("该维修站是否使用我司增值服务") @RequestParam(value = "payService", required = false) String payService,
                                @ApiParam("油漆配送时效") @RequestParam(value = "sentTime", required = false) String sentTime,
                                @ApiParam("经销商上门服务周期") @RequestParam(value = "serviceTime", required = false) String serviceTime,
                                @ApiParam("需跟进报告处理状态") @RequestParam(value = "serviceReportStatus", required = false) String serviceReportStatus,
                                @ApiParam("外勤人员姓名") @RequestParam(value = "userName", required = false) String userName,
                                @ApiParam("是否填写满意度：true:填写，false:未填写") @RequestParam(value = "type", required = false) Boolean type,
                                @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) String customerStat,
                                @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) String customerType,
                                @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String paintBrand,
                                @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        SearchVoId searchVoId;
        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
        if (clientUser.getUserType().equals(UserType.dealers)) {
            searchVoId = searchPermissionsService.getDealersStationId(userProfile, province, brand);
        } else {
            searchVoId = searchPermissionsService.searchColorReportByProvinceBrand(userProfile, province, brand);
        }
        if (searchVoId.getResultStationReportId().isEmpty()) {
            Page<ServiceResponse> page = new PageImpl<>(new ArrayList<ServiceResponse>(), pageable, 0);
            return JsonResponse.successResponseWithPageData(page);
        }

        String[] serviceTypes = null;
        String[] cities = null;
        String[] categories = null;
        String[] reportStatuses = null;
        String[] departments = null;
        String[] serviceReportStatuses = null;
        Long[] customerStats = null;
        Long[] customerTypes = null;
        String[] paintBrands = null;
        String[] productPositions = null;

        if (StringUtils.isNotEmpty(serviceType)){
            serviceTypes = serviceType.split(",");
        }
        if (!StringUtils.isEmpty(category)){
            categories = category.split(",");
        }
        if (StringUtils.isNotEmpty(city)){
            cities = city.split(",");
        }
        if (StringUtils.isNotEmpty(reportStatus)){
            reportStatuses = reportStatus.split(",");
        }
        if (StringUtils.isNotEmpty(department)){
            departments = department.split(",");
        }
        if (StringUtils.isNotEmpty(serviceReportStatus)){
            serviceReportStatuses = serviceReportStatus.split(",");
        }
        if (!StringUtils.isEmpty(paintBrand)){
            paintBrands = paintBrand.split(",");
        }
        if (!StringUtils.isEmpty(productPosition)){
            productPositions = productPosition.split(",");
        }
        if (!StringUtils.isEmpty(customerStat)){
            customerStats = (Long[]) ConvertUtils.convert(customerStat.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(customerType)){
            customerTypes = (Long[]) ConvertUtils.convert(customerType.split(","),Long.class);
        }

        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.station.id.in(searchVoId.getResultStationId()));
        if (categories!=null) {
            builder.and(qStationReport.station.category.in(categories));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStationReport.station.name.like("%" + stationName + "%"));
        }
        if (serviceEndTime != null && serviceEndTime != 0){
            builder.and(qStationReport.startServiceTime.goe(new Date(serviceStartTime)));
        }
        if (serviceStartTime != null && serviceStartTime != 0) {
            builder.and(qStationReport.endServiceTime.lt(new Date(serviceEndTime)));
        }
        if (startTime != null && startTime != 0){
            builder.and(qStationReport.updateTime.goe(new Date(startTime)));
        }
        if(endTime != null && endTime != 0) {
            builder.and(qStationReport.updateTime.lt(new Date(endTime)));
        }
        if (serviceNum != null) {
            builder.and(qStationReport.user.serviceNum.eq(serviceNum));
        }
        if (StringUtils.isNotEmpty(stationNum)){
            builder.and(qStationReport.station.stationNum.eq(stationNum));
        }
        if (paintType != null){
            builder.and(qStationReport.station.isPaint.eq(paintType?1:0));
        }
        if (cities!=null) {
            builder.and(qStationReport.station.city.in(cities));
        }
        if (reportStatuses!=null){
            builder.and(qStationReport.exceptionType.in(reportStatuses));
        }
        if (customerStats != null) {
            builder.and(qStationReport.station.customerStat.in(customerStats));
        }
        if (customerTypes != null) {
            builder.and(qStationReport.station.customerType.in(customerTypes));
        }
        if (paintBrands!=null) {
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String str: paintBrands) {
                builder.or(qStationReport.station.paintBrand.like("%" + str + "%"));
            }
            builder.and(builderOr);
        }
        if (productPositions!=null) {
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String str: productPositions) {
                builder.and(qStationReport.station.productPosition.like("%" + str + "%"));
            }
            builder.and(builderOr);
        }
        if (serviceTypes != null || serviceReportStatuses != null ) {
            //先从报告答案中找出所有填写过ids中任何一个id的答案
            QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
            BooleanBuilder regularBuilder = new BooleanBuilder();
            regularBuilder.and(qStationRegularServiceReport.deleted.eq(false));
            regularBuilder.and(qStationRegularServiceReport.enabled.eq(true));
            BooleanBuilder builderOr = new BooleanBuilder();
            boolean flag = false;
            if (serviceTypes != null) {
                flag = true;
                for (String id : serviceTypes) {
                    builderOr.or(qStationRegularServiceReport.answerId.like("%" + id + "%"));
                }
                regularBuilder.and(builderOr);
            }
            if (serviceReportStatuses != null){
                flag = true;
                for (String id : serviceReportStatuses) {
                    builderOr.or(qStationRegularServiceReport.answerId.like("%" + id + "%"));
                }
                regularBuilder.and(builderOr);
            }
            if (flag) {
                List<StationRegularServiceReport> list = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(regularBuilder);
                if (list == null || list.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> Ids = new ArrayList<>();
                for (StationRegularServiceReport report : list) {
                    if (report.getReportId() != null) {
                        Ids.add(Long.parseLong(report.getReportId()));
                    }
                }
                builder.and(qStationReport.station.id.in(Ids));
            }
        }
        if (StringUtils.isNotEmpty(userName) || departments != null) {
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
            boolean flag = false;
            if (StringUtils.isNotEmpty(userName)) {
                flag = true;
                booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            }
            if (departments != null){
                flag = true;
                booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
                booleanBuilder.and(qUserProfile.user.userType.in(UserType.admin,UserType.dealers,UserType.insiders));
                for (String str:departments){
                    booleanBuilder.or(qUserProfile.departmentList.any().name.eq(str));
                }
            }
            if (flag) {
                List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
                if (userProfileList == null || userProfileList.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> userIds = new ArrayList<>();
                for (UserProfile user : userProfileList) {
                    userIds.add(user.getUser().getId());
                }
                BooleanBuilder colorBuilder = new BooleanBuilder();
                colorBuilder.and(qStationColorReport.deleted.eq(false));
                colorBuilder.and(qStationColorReport.enabled.eq(true));
                colorBuilder.and(qStationColorReport.stationReport.station.report_finished.in(1, 2, 3));
                colorBuilder.and(qStationColorReport.stationReport.user.id.in(userIds));
                List<StationColorReport> list = (List<StationColorReport>) stationColorReportRepository.findAll(colorBuilder);
                if (list == null || list.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> ids = new ArrayList<>();
                for (StationColorReport report : list) {
                    if (report.getReportId() != null) {
                        ids.add(Long.parseLong(report.getReportId()));
                    }
                }
                builder.and(qStationReport.id.in(ids));
            }
        }
        if (payService != null || sentTime!=null || serviceTime!=null){
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            BooleanBuilder builderStationColor = new BooleanBuilder();
            builderStationColor.and(qStationColorReport.deleted.eq(false));
            builderStationColor.and(qStationColorReport.enabled.eq(true));
            boolean flag = false;
            if (payService!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+payService+"%"));
            }
            if (sentTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+sentTime+"%"));
            }
            if (serviceTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+serviceTime+"%"));
            }
            if (flag) {
                List<StationColorReport> stationColorReports = (List<StationColorReport>) stationColorReportRepository.findAll(builderStationColor);
                if (stationColorReports == null || stationColorReports.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> Ids = new ArrayList<>();
                for (StationColorReport report : stationColorReports) {
                    Ids.add(report.getStationReport().getStation().getId());
                }
                builder.and(qStationReport.station.id.in(Ids));
            }
        }
        if (type != null) {
            QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
            BooleanBuilder builderCustomer = new BooleanBuilder();
            builderCustomer.and(qCustomerRegularReport.deleted.eq(false));
            builderCustomer.and(qCustomerRegularReport.enabled.eq(true));
            builderCustomer.and(qCustomerRegularReport.type.eq(type));
            List<CustomerRegularReport> customerRegularReports = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builderCustomer);
            if (customerRegularReports == null || customerRegularReports.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            Long[] ids = new Long[customerRegularReports.size()];
            for (int i = 0; i < customerRegularReports.size(); i++) {
                ids[i] = customerRegularReports.get(i).getRegularReport().getId();
            }
            builder.and(qStationReport.id.in(ids));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "regularReport.updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<CustomerRegularReport> customerRegularReportPage = customerRegularReportRepository.findAll(builder, pageable);
        List<ServiceResponse> serviceResponseLis = new ArrayList<>();
        for (CustomerRegularReport report : customerRegularReportPage) {
            userProfile = userProfileRepository.findByUserId(report.getRegularReport().getUser().getId());
            ServiceResponse serviceResponse = new ServiceResponse(report, userProfile.getRealName());
            Integer[] num = getServiceReportNum(report.getRegularReport());
            serviceResponse.setReportNum(num);
            serviceResponseLis.add(serviceResponse);
        }
        Page<ServiceResponse> page = new PageImpl(serviceResponseLis, pageable, customerRegularReportPage.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    private Integer[] getServiceReportNum(StationReport stationReport) {
        Integer[] num = new Integer[3];
        //获取异常报告
        Station station = stationReport.getStation();
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.station.id.eq(station.getId()));
        List<StationReport> stationReportList = (List<StationReport>) stationReportRepository.findAll(builder);
        Integer complete = 0;
        Integer exception = 0;
        Integer plan = 0;
        for (StationReport report : stationReportList) {
            StationRegularServiceReport answer = stationRegularServiceReportRepository.selectAnswer(report.getId(), 181L);
            if (answer != null) {
                complete += 1;
            }
            answer = stationRegularServiceReportRepository.selectAnswer(report.getId(), 181L);
            if ((answer != null && !answer.getAnswerId().equals("181")) && !answer.getAnswerId().equals("354") || answer == null) {
                exception += 1;
            }
            answer = stationRegularServiceReportRepository.selectAnswer(report.getId(), 354L);
            if (answer != null) {
                plan += 1;
            }
        }
        num[0] = complete;
        num[1] = exception;
        num[2] = plan;
        return num;
    }

    @ApiOperation("查询维修站_并区分是否填写精益钣喷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "paint_Station", method = RequestMethod.GET)
    public JsonResponse paint_Station(Principal principal,
                                      Pageable pageable,
                                      @ApiParam("省") @RequestParam(value = "province", required = false) String province,
                                      @ApiParam("市") @RequestParam(value = "city", required = false) String city,
                                      @ApiParam("类型") @RequestParam(value = "category", required = false) String category,
                                      @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
                                      @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName,
                                      @ApiParam("是否填写") @RequestParam(value = "isPaint", required = false) Boolean isPaint,
                                      @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) String customerStat,
                                      @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) String customerType,
                                      @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String paintBrand,
                                      @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                                      @ApiParam("外勤人员姓名") @RequestParam(value = "userName", required = false) String userName,
                                      @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        SearchVoId searchVoId;
        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
        if (clientUser.getUserType().equals(UserType.dealers)) {
            searchVoId = searchPermissionsService.getDealersStationId(userProfile, province, brand);
        } else {
            searchVoId = searchPermissionsService.searchColorReportByProvinceBrand(userProfile, province, brand);
        }
        if (searchVoId.getResultStationId().isEmpty()) {
            return JsonResponse.successResponseWithData(new Object[0]);
        }

        String[] categories = null;
        String[] cities = null;
        Long[] customerStats = null;
        Long[] customerTypes = null;
        String[] paintBrands = null;
        String[] productPositions = null;

        if (StringUtils.isNotEmpty(category)){
            categories = category.split(",");
        }
        if (StringUtils.isNotEmpty(city)){
            cities = city.split(",");
        }
        if (!StringUtils.isEmpty(paintBrand)){
            paintBrands = paintBrand.split(",");
        }
        if (!StringUtils.isEmpty(productPosition)){
            productPositions = productPosition.split(",");
        }
        if (!StringUtils.isEmpty(customerStat)){
            customerStats = (Long[]) ConvertUtils.convert(customerStat.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(customerType)){
            customerTypes = (Long[]) ConvertUtils.convert(customerType.split(","),Long.class);
        }

        QStation qStation = QStation.station;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStation.deleted.eq(false));
        builder.and(qStation.enabled.eq(true));
        builder.and(qStation.checkStation.eq(true));
        builder.and(qStation.id.in(searchVoId.getResultStationId()));
        if (cities!=null) {
            builder.and(qStation.city.in(cities));
        }
        if (categories!=null) {
            builder.and(qStation.category.in(categories));
        }
        if (null != isPaint) {
            if (isPaint) {
                builder.and(qStation.isPaint.eq(1));
            } else {
                builder.and(qStation.isPaint.eq(0));
            }
        }
        if (customerStats != null) {
            builder.and(qStation.customerStat.in(customerStats));
        }
        if (customerTypes != null) {
            builder.and(qStation.customerType.in(customerTypes));
        }
        if (paintBrands!=null) {
            BooleanBuilder paintBrandBuilder = new BooleanBuilder();
            for (String pBrand:paintBrands){
                paintBrandBuilder.or(qStation.paintBrand.like("%" + pBrand + "%"));
            }
            builder.and(paintBrandBuilder);
        }
        if (productPositions!=null) {
            BooleanBuilder ppBuilder = new BooleanBuilder();
            for (String pp:productPositions){
                ppBuilder.or(qStation.productPosition.like("%" + pp + "%"));
            }
            builder.and(ppBuilder);
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStation.name.like("%" + stationName + "%"));
        }
        if (StringUtils.isNotEmpty(stationNum)) {
            builder.and(qStation.stationNum.like("%" + stationNum + "%"));
        }
        if (StringUtils.isNotEmpty(userName)) {
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
            if (userProfileList == null || userProfileList.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            List<Long> userIds = new ArrayList<>();
            for (UserProfile user : userProfileList) {
                userIds.add(user.getUser().getId());
            }
            BooleanBuilder colorBuilder = new BooleanBuilder();
            colorBuilder.and(qStationColorReport.deleted.eq(false));
            colorBuilder.and(qStationColorReport.enabled.eq(true));
            colorBuilder.and(qStationColorReport.stationReport.station.report_finished.in(1,2,3));
            colorBuilder.and(qStationColorReport.stationReport.id.in(userIds));
            List<StationColorReport> list = (List<StationColorReport>) stationColorReportRepository.findAll(booleanBuilder);
            if (list == null || list.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            List<Long> ids = new ArrayList<>();
            for (StationColorReport report : list) {
                ids.add(report.getStationReport().getStation().getId());
            }
            builder.and(qStation.id.in(ids));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "isPaint");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<Station> stationList = stationRepository.findAll(builder, pageable);
        if (stationList == null || stationList.getContent().size() <= 0) {
            return JsonResponse.successResponseWithData(new Object[0]);
        }
        List<PaintResponse> paintResponseList = new ArrayList<>();
        QStationReport qStationReport = QStationReport.stationReport;
        for (Station station : stationList) {
            builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
            builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
            builder.and(qStationReport.station.id.eq(station.getId()));
            List<StationReport> paintStationReport = (List<StationReport>) stationReportRepository.findAll(builder);
            if (paintStationReport == null || paintStationReport.size() <= 0) {
                PaintResponse paintResponse = new PaintResponse(station, false, "");
                paintResponseList.add(paintResponse);
            } else {
                userProfile = userProfileRepository.findByUserId(paintStationReport.get(0).getUser().getId());
                PaintResponse paintResponse = new PaintResponse(paintStationReport.get(0), true, userProfile.getRealName());
                User editUser = paintStationReport.get(0).getEditUser();
                if (editUser != null) {
                    userProfile = userProfileRepository.findByUserId(editUser.getId());
                    paintResponse.setEditUserName(userProfile.getRealName());
                }
                paintResponseList.add(paintResponse);
            }
        }
        Page<PaintResponse> paintResponsePage = new PageImpl(paintResponseList, pageable, stationList.getTotalElements());
        return JsonResponse.successResponseWithPageData(paintResponsePage);
    }

    @ApiOperation("查出这家维修站所有的精益版喷报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "report_paints", method = RequestMethod.GET)
    public JsonResponse getStationPaintReports(Pageable pageable, @RequestParam(name = "stationId") Long stationId) {
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
        builder.and(qStationReport.station.id.eq(stationId));
        Page<StationReport> stationReportList = stationReportRepository.findAll(builder, pageable);
        List<PaintResponse> paintResponseList = new ArrayList<>();
        for (StationReport report : stationReportList) {
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            PaintResponse paintResponse = new PaintResponse(report, true, userProfile.getRealName());
            User editUser = report.getEditUser();
            if (editUser != null) {
                userProfile = userProfileRepository.findByUserId(editUser.getId());
                paintResponse.setEditUserName(userProfile.getRealName());
            }
            paintResponseList.add(paintResponse);
        }
        Page<PaintResponse> paintResponsePage = new PageImpl(paintResponseList, pageable, stationReportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(paintResponsePage);
    }


    @ApiOperation("查询维修站_并列出已经填写过的维修站")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "paint", method = RequestMethod.GET)
    public JsonResponse paint(Principal principal,
                              Pageable pageable,
                              @ApiParam("省") @RequestParam(value = "province", required = false) String province,
                              @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                              @ApiParam("类型") @RequestParam(value = "category", required = false) String category,
                              @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
                              @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName,
                              @ApiParam("报告起始提交时间") @RequestParam(value = "startTime", required = false) Long startTime,
                              @ApiParam("报告结束提交时间") @RequestParam(value = "endTime", required = false) Long endTime,
                              @ApiParam("服务项目") @RequestParam(value = "serviceType", required = false) String serviceType,
                              @ApiParam("服务次数") @RequestParam(value = "serviceNum", required = false) Integer serviceNum,
                              @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                              @ApiParam("所属部门") @RequestParam(value = "department", required = false) String department,
                              @ApiParam("该维修站是否使用我司增值服务") @RequestParam(value = "payService", required = false) String payService,
                              @ApiParam("油漆配送时效") @RequestParam(value = "sentTime", required = false) String sentTime,
                              @ApiParam("经销商上门服务周期") @RequestParam(value = "serviceTime", required = false) String serviceTime,
                              @ApiParam("需跟进报告处理状态") @RequestParam(value = "serviceReportStatus", required = false) String serviceReportStatus,
                              @ApiParam("外勤人员姓名") @RequestParam(value = "userName", required = false) String userName,
                              @ApiParam("是否填写满意度：true:填写，false:未填写") @RequestParam(value = "type", required = false) Boolean type,
                              @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) String customerStat,
                              @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) String customerType,
                              @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String paintBrand,
                              @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        SearchVoId searchVoId;
        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
        if (clientUser.getUserType().equals(UserType.dealers)) {
            searchVoId = searchPermissionsService.getDealersStationId(userProfile, province, brand);
        } else {
            searchVoId = searchPermissionsService.searchColorReportByProvinceBrand(userProfile, province, brand);
        }
        if (searchVoId.getResultStationReportId().isEmpty()) {
            return JsonResponse.successResponseWithData(new Object[0]);
        }

        String[] serviceTypes = null;
        String[] cities = null;
        String[] categories = null;
        String[] departments = null;
        String[] serviceReportStatuses = null;
        Long[] customerStats = null;
        Long[] customerTypes = null;
        String[] paintBrands = null;
        String[] productPositions = null;

        if (StringUtils.isNotEmpty(serviceType)){
            serviceTypes = serviceType.split(",");
        }
        if (StringUtils.isNotEmpty(city)){
            cities = city.split(",");
        }
        if (!StringUtils.isEmpty(category)){
            categories = category.split(",");
        }
        if (StringUtils.isNotEmpty(department)){
            departments = department.split(",");
        }
        if (StringUtils.isNotEmpty(serviceReportStatus)){
            serviceReportStatuses = serviceReportStatus.split(",");
        }
        if (!StringUtils.isEmpty(paintBrand)){
            paintBrands = paintBrand.split(",");
        }
        if (!StringUtils.isEmpty(productPosition)){
            productPositions = productPosition.split(",");
        }
        if (!StringUtils.isEmpty(customerStat)){
            customerStats = (Long[]) ConvertUtils.convert(customerStat.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(customerType)){
            customerTypes = (Long[]) ConvertUtils.convert(customerType.split(","),Long.class);
        }


        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.station.id.in(searchVoId.getResultStationId()));

        if (categories!=null) {
            builder.and(qStationReport.station.category.in(categories));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStationReport.station.name.like("%" + stationName + "%"));
        }
        if (startTime != null && startTime != 0){
            builder.and(qStationReport.updateTime.goe(new Date(startTime)));
        }
        if(endTime != null && endTime != 0) {
            builder.and(qStationReport.updateTime.lt(new Date(endTime)));
        }
        if (serviceNum != null) {
            builder.and(qStationReport.user.serviceNum.eq(serviceNum));
        }
        if (StringUtils.isNotEmpty(stationNum)){
            builder.and(qStationReport.station.stationNum.eq(stationNum));
        }
        if (cities!=null) {
            builder.and(qStationReport.station.city.in(cities));
        }
        if (customerStats != null) {
            builder.and(qStationReport.station.customerStat.in(customerStats));
        }
        if (customerTypes != null) {
            builder.and(qStationReport.station.customerType.in(customerTypes));
        }
        if (paintBrands!=null) {
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String str: paintBrands) {
                builder.or(qStationReport.station.paintBrand.like("%" + str + "%"));
            }
            builder.and(builderOr);
        }
        if (productPositions!=null) {
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String str: productPositions) {
                builder.and(qStationReport.station.productPosition.like("%" + str + "%"));
            }
            builder.and(builderOr);
        }
        if (serviceTypes != null || serviceReportStatuses != null ) {
            //先从报告答案中找出所有填写过ids中任何一个id的答案
            QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
            BooleanBuilder regularBuilder = new BooleanBuilder();
            regularBuilder.and(qStationRegularServiceReport.deleted.eq(false));
            regularBuilder.and(qStationRegularServiceReport.enabled.eq(true));
            BooleanBuilder builderOr = new BooleanBuilder();
            boolean flag = false;
            if (serviceTypes != null) {
                flag = true;
                for (String id : serviceTypes) {
                    builderOr.or(qStationRegularServiceReport.answerId.like("%" + id + "%"));
                }
                regularBuilder.and(builderOr);
            }
            if (serviceReportStatuses != null){
                flag = true;
                for (String id : serviceReportStatuses) {
                    builderOr.or(qStationRegularServiceReport.answerId.like("%" + id + "%"));
                }
                regularBuilder.and(builderOr);
            }
            if (flag) {
                List<StationRegularServiceReport> list = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(regularBuilder);
                if (list == null || list.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> Ids = new ArrayList<>();
                for (StationRegularServiceReport report : list) {
                    if (report.getReportId() != null) {
                        Ids.add(Long.parseLong(report.getReportId()));
                    }
                }
                builder.and(qStationReport.station.id.in(Ids));
            }
        }
        if (StringUtils.isNotEmpty(userName) || departments != null) {
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
            boolean flag = false;
            if (StringUtils.isNotEmpty(userName)) {
                flag = true;
                booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            }
            if (departments != null){
                flag = true;
                booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
                booleanBuilder.and(qUserProfile.user.userType.in(UserType.admin,UserType.dealers,UserType.insiders));
                for (String str:departments){
                    booleanBuilder.or(qUserProfile.departmentList.any().name.eq(str));
                }
            }
            if (flag) {
                List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
                if (userProfileList == null || userProfileList.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> userIds = new ArrayList<>();
                for (UserProfile user : userProfileList) {
                    userIds.add(user.getUser().getId());
                }
                BooleanBuilder colorBuilder = new BooleanBuilder();
                colorBuilder.and(qStationColorReport.deleted.eq(false));
                colorBuilder.and(qStationColorReport.enabled.eq(true));
                colorBuilder.and(qStationColorReport.stationReport.station.report_finished.in(1, 2, 3));
                colorBuilder.and(qStationColorReport.stationReport.user.id.in(userIds));
                List<StationColorReport> list = (List<StationColorReport>) stationColorReportRepository.findAll(colorBuilder);
                if (list == null || list.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> ids = new ArrayList<>();
                for (StationColorReport report : list) {
                    if (report.getReportId() != null) {
                        ids.add(Long.parseLong(report.getReportId()));
                    }
                }
                builder.and(qStationReport.id.in(ids));
            }
        }
        if (payService != null || sentTime!=null || serviceTime!=null){
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            BooleanBuilder builderStationColor = new BooleanBuilder();
            builderStationColor.and(qStationColorReport.deleted.eq(false));
            builderStationColor.and(qStationColorReport.enabled.eq(true));
            boolean flag = true;
            if (payService!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+payService+"%"));
            }
            if (sentTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+sentTime+"%"));
            }
            if (serviceTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+serviceTime+"%"));
            }
            if (flag) {
                List<StationColorReport> stationColorReports = (List<StationColorReport>) stationColorReportRepository.findAll(builderStationColor);
                if (stationColorReports == null || stationColorReports.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> Ids = new ArrayList<>();
                for (StationColorReport report : stationColorReports) {
                    Ids.add(report.getStationReport().getStation().getId());
                }
                builder.and(qStationReport.station.id.in(Ids));
            }
        }
        if (type != null) {
            QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
            BooleanBuilder builderCustomer = new BooleanBuilder();
            builderCustomer.and(qCustomerRegularReport.deleted.eq(false));
            builderCustomer.and(qCustomerRegularReport.enabled.eq(true));
            builderCustomer.and(qCustomerRegularReport.type.eq(type));
            List<CustomerRegularReport> customerRegularReports = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builderCustomer);
            if (customerRegularReports == null || customerRegularReports.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            Long[] ids = new Long[customerRegularReports.size()];
            for (int i = 0; i < customerRegularReports.size(); i++) {
                ids[i] = customerRegularReports.get(i).getRegularReport().getId();
            }
            builder.and(qStationReport.id.in(ids));
        }

        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<StationReport> stationReports = stationReportRepository.findAll(builder, pageable);
        List<PaintResponse> paintResponseList = new ArrayList<>();
        List<Long> paintReportStationId = new ArrayList<>();
        for (StationReport report : stationReports) {
            if (!paintReportStationId.contains(report.getStation().getId())) {
                userProfile = userProfileRepository.findByUserId(report.getUser().getId());
                PaintResponse paintResponse = new PaintResponse(report, true, userProfile.getRealName());
                paintResponseList.add(paintResponse);
                paintReportStationId.add(report.getStation().getId());
            }
        }
        Page<PaintResponse> paintResponsePage = new PageImpl(paintResponseList, pageable, paintResponseList.size());
        return JsonResponse.successResponseWithPageData(paintResponsePage);
    }


    @ApiOperation("查询处理满意度的结果")
    @RequestMapping(value = "getCustomerNote", method = RequestMethod.GET)
    public JsonResponse getCustomerNote(Principal principal,
                                        @ApiParam("满意度报告ID") @RequestParam(value = "customerReportId", required = false) Long customerReportId) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
//        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.customerReport.id.eq(customerReportId));
        CustomerRegularReport customerRegularReport = customerRegularReportRepository.findOne(builder);
        if (customerRegularReport != null && StringUtils.isNotEmpty(customerRegularReport.getManageNote())) {
            User user = customerRegularReport.getManageUser();
            String manageName = "";
            if (user != null) {
                UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
                if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
                    manageName = userProfile.getRealName();
                }
            }
            String[] str = new String[3];
            str[0] = manageName;
            str[1] = customerRegularReport.getUpdateTimeStr();
            str[2] = customerRegularReport.getManageNote();
            return JsonResponse.successResponseWithData(str);
        } else {
            return JsonResponse.successResponseWithData(new Object[0]);
        }
    }

}
